package com.pxml2pdf;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.pxml2pdf.pdf.NodeFactory;
import com.pxml2pdf.pdf.X2PConverter;
import com.pxml2pdf.pdf.Node.BaseNode;
import com.pxml2pdf.pdf.Node.DivNode;
import com.pxml2pdf.pxml.Ppage;
import com.pxml2pdf.pxml.Pxml;
import com.pxml2pdf.utility.X2pUtility;

public class Pxml2pdf {
	private static final String ROOT_NAME = "pxml";
	private static final String PAGE_NAME = "page";
	private static final String NODE_NAME = "node";
	private Pxml pxmlObj = new Pxml();

	private String fileName;
	private String pw;

	public Pxml2pdf(String html, String tmpFileName,String password) throws DocumentException {
		fileName = tmpFileName;
		pw = password;
		html = html.replaceAll("&nbsp", "");
		html = html.replaceAll("&(?!amp;|lt;|gt;|quot;|apos;|#xA;)", "&amp;");
		Document document = DocumentHelper.parseText(html);
		Element root = document.getRootElement();
		if (ROOT_NAME.equals(root.getName())) {
			pxmlObj.setFormat(root.attributeValue("format"));
			pxmlObj.setId(root.attributeValue("id"));
			pxmlObj.setLeft(X2pUtility.ps2d(root.attributeValue("left")));
			pxmlObj.setTop(X2pUtility.ps2d(root.attributeValue("top")));
			pxmlObj.setWidth(X2pUtility.ps2d(root.attributeValue("width")));
			@SuppressWarnings("unchecked")
			List<Element> pageList = root.elements(PAGE_NAME);
			for (Element page : pageList) {
				float maxHeight = 0f;
				Ppage ppage = new Ppage();
				pxmlObj.getPpageList().add(ppage);
				ppage.setElementID(page.attributeValue("elementID"));
				ppage.setHeight(X2pUtility.ps2d(page.attributeValue("height")));
				ppage.setIndex(page.attributeValue("index"));
				@SuppressWarnings("unchecked")
				List<Element> nodeList = page.elements(NODE_NAME);
				for (Element node : nodeList) {
					BaseNode bn = NodeFactory.createNode(node.attributeValue("nodeType"));
					if (bn != null) {
						bn.parse(node);
						ppage.getPnodeList().add(bn);
						if (!DivNode.class.isInstance(bn)) {
							float top = bn.getTop() + bn.getHeight();
							if (maxHeight < top) {
								maxHeight = top;
							}
						}
					}
				}
				if (ppage.getHeight() < maxHeight) {
					ppage.setHeight(maxHeight);
				}
			}
		}
	}

	public void Convert() {
		X2PConverter converter = new X2PConverter();
		converter.Convert(pxmlObj, fileName,pw);
	}
}
